

// Create a database

class LevelDBClass {
    constructor(path){
        this.db =new Level(path, { valueEncoding: 'json' });
    }
    async set(key, value) {
        return new Promise((resolve, reject) => {
            this.db.put(key, value, (err) => {
                if (err) {
                    console.error(err);
                    resolve(false);
                } else {
                    resolve(true);
                }
            });
        });
    }
     
    async get(key) {
        return new Promise((resolve, reject) => {
            this.db.get(key, (err, value) => {
                if (err) {
                    if (err.code == 'LEVEL_NOT_FOUND'){
                        resolve(null);
                    }else{
                        console.error(err);
                        resolve(null);
                    }
                } else {
                    resolve(value);
                }
            });
        });
    }
    
    async delete(key) {
        return new Promise((resolve, reject) => {
            this.db.del(key, (err) => {
                if (err) {
                    console.error(err);
                    resolve(false);
                } else {
                    resolve(true);
                }
            });
        });
    }
    
    async listKey() {
        return this.db.keys().all();
    }

    close(callback){
        this.db.close(callback);
    }
}
module.exports = {
    LevelDBClass
};
